home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: Pointer Conversion
- Date: 21 Jan 1996 23:14:19 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4duhcb$7if@news.iag.net>
- References: <4ds4jq$fo4@su3.in.net> <4ds6s3$ft6@su3.in.net>
- NNTP-Posting-Host: pm2-orl13.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <4ds6s3$ft6@su3.in.net>, poundss@in.net says...
- >
- >poundss@in.net (Sam Pounds) wrote:
- >
- >
- >>char *my_strcat(const char *a, const char *b)
- >>{
- >> char done[1024];
- >> char *p = done;
- >
- >> while (*a)
- >> *p++ = *a++;
- >> while (*b)
- >> *p++ = *b++;
- >> *p = '\0';
- >> return done; /* this is the suspicious pointer conversion error */
-
- The problem here is that the memory allocated to create done, when this
- function started, is deallocated, when it exits. So you are returning a
- pointer to an invalid memory location.
-
- >>}
- >
- >Sorry, it just dawned on me.
- >char *done = (char *)malloc(1024);
- >
- >But if anyone could tell me how I could just alloc the
- >necessary memory for the two pointers I would appreciate it.
- >Sorry again.
-
- I'm afraid I don't understand your question. What two pointers are you
- do you want to allocate memory for?
-
- If you want your function to return a pointer to a new array containing the
- concatenated string (instead of concatenating b to a, like in strcat), you
- only have a few options:
-
- 1. Define a static char array for the result (either global or using the
- static storage qaulifier). Since only one char array will exist, its
- contents will be overwritten on each call to my_strcat. The caller
- would probably need to strcpy it elsewhere before the next call.
-
- 2. Allocate a new dynamic array for the result. This is equivalent to your
- malloc solution. The caller will have to free this memory, when it is
- no longer needed.
-
- 3. Define my_strcat to accept a char pointer to an external array and
- write the result there. The caller would be responsible for passing
- a valid pointer to a char array of the correct size.
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-